package com.lucky.xyt.modular.code.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.SqlRunner;
import com.lucky.xyt.modular.system.model.TableField;

/**
 * 获取数据库所有的表
 *
 * @author bobo
 * @date 2017-12-04-下午1:37
 */
@Service
public class TableService {

    @Value("${spring.datasource.db-name}")
    private String dbName;

    /**
     * 获取当前数据库所有的表信息
     */
    public List<Map<String, Object>> getAllTables() {
        String sql = "select TABLE_NAME as tableName,TABLE_COMMENT as tableComment from information_schema.`TABLES` where TABLE_SCHEMA = '" + dbName + "'";
        return SqlRunner.db().selectList(sql);
    }

	public List<TableField> getTableFields(String tablename) {
		String sql ="select COLUMN_NAME AS name,COLUMN_NAME AS javaField,DATA_TYPE jdbcType,COLUMN_COMMENT AS comments,"
				+ "CASE WHEN DATA_TYPE = 'int' THEN 'Integer' WHEN DATA_TYPE = 'varchar' THEN 'String' WHEN DATA_TYPE = 'float' THEN 'Double' ELSE 'String' END AS javaType,"
				+"CASE WHEN COLUMN_KEY ='PRI' THEN '1' ELSE '' END AS isPk,"
				+"CASE WHEN IS_NULLABLE ='NO' THEN 0 WHEN IS_NULLABLE ='YES' THEN 1 END AS isNull " 
				+"from information_schema.columns where table_schema = '"+dbName+"' and table_name = '"+tablename+"'";
		List<Map<String, Object>> list =  SqlRunner.db().selectList(sql);
		List<TableField> listTableField =  new ArrayList<TableField>();
		
		for (Map<String, Object> map : list) {
			listTableField.add(JSON.parseObject(JSON.toJSONString(map), TableField.class));
		}
		return  listTableField;
		
	}
}
